package cn.emailChat.ai.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;
import java.util.stream.IntStream;

/**
 * @Description 声明队列 + JSON 转换器
 * @Author susu
 * @Date 2025/8/18
 */
@Configuration
@EnableRabbit
public class RabbitConfig {

    // 方案B建议通过 exchange + routingKey 分发；也兼容“直发多个队列”
    @Value("${mail.reply.partition.exchange:auto.reply.x}")
    private String replyExchange; // 若不用交换机，可设为空字符串 ""

    // routingKey 前缀，例如 auto.reply.p0 / auto.reply.p1 / auto.reply.p2
    @Value("${mail.reply.partition.routing-prefix:auto.reply.p}")
    private String replyRoutingPrefix;

    // 如果直发队列，配置三个队列的前缀：auto.reply.q.p0/1/2
    @Value("${mail.reply.partition.queue-prefix:auto.reply.q.p}")
    private String replyQueuePrefix;

    @Value("${mail.reply.partition.count:3}")
    private int partitionCount; // 目前为 3
    // 交换机 + 分区队列 + 绑定
    @Bean
    public Declarables autoReplyPartitionedTopology() {
        DirectExchange ex = new DirectExchange(replyExchange, true, false);

        List<Declarable> decls = new ArrayList<>();
        decls.add(ex);

        IntStream.range(0, partitionCount) // partitionCount=3 等，从配置注入
                .forEach(i -> {
                    String qn = join(replyQueuePrefix, i);     // e.g. auto.reply.q.p.0
                    String rk = join(replyRoutingPrefix, i);   // e.g. auto.reply.p.0

                    Queue q = QueueBuilder.durable(qn).build();
                    Binding b = BindingBuilder.bind(q).to(ex).with(rk);

                    decls.add(q);
                    decls.add(b);
                });

        return new Declarables(decls);
    }

    /** 统一“前缀.索引”的拼接，避免出现 "..0" 或无分隔符的情况 */
    private static String join(String prefix, int idx) {
        String p = (prefix == null) ? "" : prefix.trim();
        if (p.endsWith(".")) p = p.substring(0, p.length() - 1);
        return p.isEmpty() ? String.valueOf(idx) : p + "." + idx;
    }

    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}